<template>
	<div :class="`q-box ${isEdit ? 'border' : ''}`">
		<Input ref="input" v-if="question.questionType == 'input'" :question="question" :index="index" />
		<Textarea ref="textarea" v-if="question.questionType == 'textarea'" :question="question"
			:index="index"></Textarea>
		<Radio ref="radio" v-if="question.questionType == 'radio'" :question="question" :index="index" />
		<Checkbox ref="checkbox" v-if="question.questionType == 'checkbox'" :question="question" :index="index" />
		<Select ref="select" v-if="question.questionType == 'select'" :question="question" :index="index"></Select>
		<Title ref="title" v-if="question.questionType == 'title'" :question="question" :index="index"></Title>
		<QText ref="text" v-if="question.questionType == 'text'" :question="question" :index="index" />

		<div class="q-btn">
			<el-button type="primary" text icon="CirclePlus" size="small" @click="insertQuestion">新题</el-button>
			<el-button type="primary" text icon="Edit" size="small" @click="editQuestion">编辑</el-button>
			<el-button type="primary" text icon="CopyDocument" size="small" @click="copyQuestion">复制</el-button>
			<el-button type="primary" text icon="Delete" size="small" @click="delQuestion">删除</el-button>
			<el-button type="primary" text icon="Upload" size="small" @click="upQuestion">上移</el-button>
			<el-button type="primary" text icon="Download" size="small" @click="downQuestion">下移</el-button>
		</div>

		<div class="q-config" v-if="isEdit">
			<!-- 标题 -->
			<div class="topic-title">
				<!-- <span>标题：</span> -->
				<el-input v-model="question.questionName" type="textarea" @focus="focusTitle" rows="2"
					style="width:100%" placeholder="请输入标题" ref="questionTitle"></el-input>
			</div>

			<!-- 规则配置 -->
			<div class="topic-rules">
				<!-- 题型 -->
				<label>选择题型：</label>
				<el-select v-model="question.questionType" placeholder="请选择题型" size="small" style="width:20%">
					<el-option v-for="dict in dict.question_type" :key="dict.dictValue" :label="dict.dictName" :value="dict.dictValue">
					</el-option>
				</el-select>

				<!-- 方向 -->
				<template v-if="questionClass == 's' && question.questionType != 'select'">
					<label style="margin-left: 10px;">显示方向：</label>
					<el-select v-model="question.optionDisplay" placeholder="请选择方向" size="small" style="width:20%">
						<el-option v-for="dict in dict.option_direction" :key="dict.dictValue" :label="dict.dictName" :value="dict.dictValue">
						</el-option>
					</el-select>
				</template>

				<!-- 默认值 -->
				<template v-if="questionClass != 't'">
					<label style="margin-left: 10px;">默认值：</label>
					<template v-if="questionClass == 's' && question.questionType != 'checkbox'">
						<el-select v-model="question.defaultValue" placeholder="请选择默认值" clearable size="small"
							style="width:20%">
							<el-option v-for="(option, oIndex) in question.options" :key="oIndex"
								:label="option.optionText" :value="option.optionText"></el-option>
						</el-select>
					</template>

					<template v-if="question.questionType == 'checkbox'">
						<el-select v-model="question.defaultValue" placeholder="请选择默认值" multiple clearable size="small"
							style="width:20%">
							<el-option v-for="(option, oIndex) in question.options" :key="oIndex"
								:label="option.optionText" :value="option.optionText"></el-option>
						</el-select>
					</template>

					<template v-if="questionClass == 'i'">
						<el-input v-model="question.defaultValue" placeholder="请输入默认值" size="small" style="width: 24%;"></el-input>
					</template>
				</template>
			</div>

			<!-- 选项列表 -->
			<div class="topic-option" v-if="questionClass == 's'">
				<ul class="topic-list">
					<li class="topic-item" v-for="(option, optionIndex) in question.options" :key="optionIndex">
						<el-input v-model="option.optionText" @focus="focusOption" @keyup.enter.native="keyupOption" placeholder="请输入选项" size="small" ref="optionInput" :maxlength=128 style="width: 30%;" />
						<el-icon :size="20" @click="addOption" title="添加"><i class="iconfont icon-r-add"></i></el-icon>
						<el-icon :size="20" @click="delOption(optionIndex)" title="删除"><i class="iconfont icon-r-del"></i></el-icon>
						<el-icon :size="20" @click="upOption(optionIndex)" title="上移"><i class="iconfont icon-r-up"></i></el-icon>
						<el-icon :size="20" @click="downOption(optionIndex)" title="下移"><i class="iconfont icon-r-down"></i></el-icon>
						<el-checkbox v-model="option.isExtend" true-label="1" false-label="" style="font-size: 12px;margin-left: 10px;">备注</el-checkbox>
					</li>
				</ul>
			</div>

			<div class="topic-logic">
				<!-- 必填 -->
				<el-checkbox v-model="question.validateRule" true-label="notEmpty" false-label=""
					style="margin-right: 15px;">必填</el-checkbox>

				<!-- 初始隐藏 -->
				<el-checkbox v-model="question.showOrHide" true-label="1" false-label="0"
					style="margin-right: 15px;">初始隐藏</el-checkbox>

				<!-- 只读 -->
				<el-checkbox v-model="question.notEdit" true-label="1" false-label="0"
					style="margin-right: 15px;">只读</el-checkbox>
			</div>

			<div class="topic-finish">
				<el-button class="w-btn" type="warning" @click="saveQuestion">保存编辑</el-button>
				<el-button class="w-btn" type="default" @click="cancelEdit">取消编辑</el-button>
			</div>
		</div>

	</div>
</template>
<script>
import Input from './components/Input.vue';
import Title from './components/Title.vue';
import Textarea from './components/Textarea.vue';
import Radio from './components/Radio.vue';
import Checkbox from './components/Checkbox.vue';
import Select from './components/Select.vue';
import QText from './components/Text.vue';
import { ArrayUtil } from "@/utils/arrayUtil";
import { getDicts } from "@/api/dict";

export default {
	name: 'Question',
	components: { Input, Title, Textarea, Radio, Checkbox, Select, QText },
	props: {
		index: Number,
		surveyId: [String],
		question: {
			type: Object,
			default: {}
		}
	},
	data() {
		return {
			isEdit: false,
			questionClass: '',
			dict: {
				question_type: [],
				option_direction: []
			}
		}
	},
	async mounted() {
		this.initClass();
		this.refreshOption();
		this.dict.question_type = await getDicts("question_type");
		this.dict.option_direction = await getDicts("option_direction");
	},
	methods: {
		initClass() {
			switch (this.question.questionType) {
				case 'input':
				case 'textarea':
				default:
					this.questionClass = 'i';
					break;
				case 'radio':
				case 'checkbox':
				case 'select':
					this.questionClass = 's';
					break;
				case 'text':
				case 'title':
					this.questionClass = 't'
					break;
			}
		},
		insertQuestion() { this.$emit('insertQuestion', this.index) },
		editQuestion() {
			this.isEdit = true
		},
		saveQuestion() {
			// 对于多选题型，结果是一个数组，将数组转换为字符串存储
			if (this.question.questionType == 'checkbox') {
				if(this.question.defaultValue){
					this.question.defaultValue = this.question.defaultValue.join(',');
				} else {
					this.question.defaultValue = ''
				}
			}
			if (this.questionClass == 't') {
				this.question.questionNo = null
			}
			this.$emit('saveQuestion', this.question, (res) => {
				console.log(res)
				this.isEdit = false
				this.question = res
				if (this.question.questionType == 'checkbox' && this.question.defaultValue) {
					this.question.defaultValue = this.question.defaultValue.split(',');
				}
			})
		},
		copyQuestion() { this.$emit('copyQuestion', this.index) },
		delQuestion() { this.$emit('delQuestion', this.index) },
		upQuestion() { this.$emit('upQuestion', this.index) },
		downQuestion() { this.$emit('downQuestion', this.index) },
		addOption() {
			let option = {
				optionId: '',
				questionId: this.question.questionId,
				optionCode: this.question.options.length + 1,
				optionText: '选项' + (this.question.options.length + 1) * 1,
				optionNo: this.question.options.length + 1,
				hideQuestion: '',
				showQuestion: '',
				isExtend: '',
				logicSymbol: '',
				surveyId: this.surveyId,
			};
			this.question.options.push(option);
			if (this.isEdit) {
				setTimeout(() => {
					this.$refs['optionInput'][this.question.options.length - 1].focus()
				}, 50)
			}
		},
		keyupOption() {
			this.addOption();
		},
		delOption(index) {
			if (this.question.options.length === 1) {
				this.$message({
					type: 'warning',
					message: '至少得留一项吧!'
				});
				return;
			}
			let optionId = this.question.options[index].optionId;
			if (optionId) {
				this.$confirm('确定要删除吗?', '确认提醒', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
					this.question.options.splice(index, 1);
				});
			} else {
				this.question.options.splice(index, 1);
			}
		},
		upOption(index) {
			if (this.question.options.length == 0 || index === 0) {
				return;
			}
			this.question.options = ArrayUtil.moveUp(this.question.options, index);
		},
		downOption(index) {
			if (this.question.options.length == 0 || index === this.question.options.length - 1) {
				return;
			}
			this.question.options = ArrayUtil.moveDown(this.question.options, index);
		},
		refreshOption() {
			if (this.question.options.length == 0 && this.questionClass == 's') {
				this.addOption();
				//this.addOption();	
			}
			if (this.questionClass != 's') {
				this.question.options.length == 0
			}
			if (this.question.options.length == 1 && this.question.options[0].qotionId == null) {
				this.question.options = []
				this.addOption();
			}
		},
		focusTitle() {
			if (this.question.questionName == '请输入标题') {
				this.question.questionName = '';
			}
		},
		focusOption(obj) {
			let val = obj.target.value;
			if (val.indexOf('选项') > -1) {
				obj.target.value = '';
			}
		},
		// 取消编辑
		cancelEdit() {
			this.isEdit = false
		}
	},
	watch: {
		'question.questionType': {
			handler: function (val) {
				this.question.questionType = val
				this.initClass();
				this.refreshOption();
			},
		},
		'isEdit': {
			handler: function (val) {
				if (val) {
					setTimeout(() => {
						this.$refs['questionTitle'].focus()
					}, 50)
				}
			},
		}
	}
}
</script>
<style>
.el-button--small {
	padding: 0;
}
</style>